package com.mg;


import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayTest {

    @Test
    public void Test2ArrayType() {
        /**
         * 一般情况下，对参数Collection<? extends E> c而言，c.toArray()返回的是Object[]类型
         */
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        System.out.println(list.toArray().getClass());

        /**
         * 但是返回的也有可能不是Object[]类型，请看下面的代码：
         */
        Father[] fathers = new Son[]{};
        // 打印结果为class [Lcom.coolcoding.code.Son;
        System.out.println(fathers.getClass());

        List<String> strList = new MyList();
        // 打印结果为class [Ljava.lang.String;
        System.out.println(strList.toArray().getClass());
    }

    @Test
    public void TestArraycopyOfSystem() {

        String[] elementData = new String[] { "a", "b", "c", "d", "e", "f" };
        int index = 2;
        int size = elementData.length;
        //检查是否需要扩容 ，略
        String[] newElementData = new String[] { "a", "b", "c", "d", "e", "f", "" };
        elementData = newElementData;

        System.arraycopy(elementData, index, elementData, index + 1, size - index);
        //再将index= 2的位置替换成需要在该位置插入的值"x"
        elementData[index] = "x";
        System.out.println(Arrays.toString(elementData));
    }

    @Test
    public void TestArraysCopyOf01() {
        String[] elementData = new String[] { "a", "b", "c", "d", "e", "f" };
        Object[] obj = Arrays.copyOf(elementData, elementData.length, Object[].class);
        System.out.println(Arrays.toString(obj));
    }

    @Test
    public void TestArrayscopyOf02() {
        String[] elementData = new String[] { "a", "b", "c", "d", "e", "f" };
        elementData = Arrays.copyOf(elementData, 10);
        System.out.println(Arrays.toString(elementData));
    }

    @Test
    public void TestRemoveByIndex() {
        int x = 10;
        System.out.println(--x);

        String[] elementData = new String[] { "a", "b", "c", "d", "e", "f" };

        int size = elementData.length;
        int index  = 5;

        int numMoved = elementData.length - index - 1;

        if (numMoved > 0) {
            System.arraycopy(elementData, index + 1, elementData, index, numMoved);
        }
        elementData[--size] = null;

        System.out.println(Arrays.toString(elementData));
    }
}


class Father {}

class Son extends Father {}

class MyList extends ArrayList<String> {
    /**
     * 子类重写父类的方法，返回值可以不一样
     * 但这里只能用数组类型，换成Object就不行
     * 应该算是java本身的bug
     */
    @Override
    public String[] toArray() {
        // 为了方便举例直接写死
        return new String[]{"1", "2", "3"};
    }
}